/**
 * 厦门大学计算机专业 | 华为开发专家(HDE)
 * 专注《零基础学编程系列》  http://lblbc.cn/blog
 * 包含：鸿蒙 | Java | 安卓 | 前端 | Flutter | iOS | 小程序
 * 公众号：蓝不蓝编程
 */
import { Context } from '@kit.AbilityKit'
import { relationalStore } from '@kit.ArkData'
import { Note } from '../beans/Note';

// 假设 RelationalError 和 RelationalStore 是已定义的类型
interface RelationalError {
  code: number
  message: string
}

// 定义 STORE_CONFIG 的接口
interface StoreConfig {
  name: string
  securityLevel: relationalStore.SecurityLevel
}

export class DbManager {
  private static _instance: DbManager
  private context: Context

  private STORE_CONFIG: StoreConfig = {
    name: "lblbc.db",
    securityLevel: relationalStore.SecurityLevel.S1,
  }
  private tableName: string = "Note"

  private constructor() {
  }

  public static getInstance(): DbManager {
    if (!DbManager._instance) {
      DbManager._instance = new DbManager()
    }
    return DbManager._instance
  }

  public init(context: Context): void {
    this.context = context
    this.createTable()
  }

  public createTable(): void {
    relationalStore.getRdbStore(this.context, this.STORE_CONFIG,
      (err: RelationalError | null, rdbStore: relationalStore.RdbStore) => {
        rdbStore.executeSql("CREATE TABLE IF NOT EXISTS " + this.tableName +
          " (id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT NOT NULL)")
      })
  }

  public insert(note: Note): void {
    relationalStore.getRdbStore(this.context, this.STORE_CONFIG,
      (err: RelationalError | null, rdbStore: relationalStore.RdbStore) => {
        rdbStore.insert(this.tableName, { "content": note.content })
      })
  }

  public update(note: Note): void {
    relationalStore.getRdbStore(this.context, this.STORE_CONFIG,
      (err: RelationalError | null, rdbStore: relationalStore.RdbStore) => {
        let predicates = new relationalStore.RdbPredicates(this.tableName)
        predicates.equalTo("id", note.id)
        rdbStore.update({ "content": note.content }, predicates)
      })
  }

  public queryAll(callback: (noteList: Note[]) => void): void {
    relationalStore.getRdbStore(this.context, this.STORE_CONFIG,
      (err: RelationalError | null, rdbStore: relationalStore.RdbStore) => {
        let predicates = new relationalStore.RdbPredicates(this.tableName)
        rdbStore.query(predicates, null, (err, resultSet) => {
          if (err) {
            console.error(`Query failed, code is ${err.code},message is ${err.message}`)
            return
          }
          let noteList: Note[] = []
          while (resultSet.goToNextRow()) {
            let note = new Note()
            note.id = resultSet.getLong(0)
            note.content = resultSet.getString(1)
            noteList.push(note)
          }
          callback(noteList)
        })
      })
  }

  public queryById(id: number, callback: (note: Note) => void): void {
    relationalStore.getRdbStore(this.context, this.STORE_CONFIG,
      (err: RelationalError | null, rdbStore: relationalStore.RdbStore) => {
        let predicates = new relationalStore.RdbPredicates(this.tableName)
        predicates.equalTo("id", id)
        rdbStore.query(predicates, null, (err, resultSet) => {
          if (err) {
            console.error(`Query failed, code is ${err.code},message is ${err.message}`)
            return
          }
          let note: Note = new Note()
          if (resultSet.goToNextRow()) {
            note.id = resultSet.getLong(0)
            note.content = resultSet.getString(1)
          }
          callback(note)
        })
      })
  }

  public deleteAll(): void {
    relationalStore.getRdbStore(this.context, this.STORE_CONFIG,
      (err: RelationalError | null, rdbStore: relationalStore.RdbStore) => {
        rdbStore.executeSql("DELETE FROM " + this.tableName)
      })
  }

  public deleteById(id: number): void {
    relationalStore.getRdbStore(this.context, this.STORE_CONFIG,
      (err: RelationalError | null, rdbStore: relationalStore.RdbStore) => {
        let predicates = new relationalStore.RdbPredicates(this.tableName)
        predicates.equalTo("id", id)
        rdbStore.delete(predicates)
      })
  }
}
